package ljl.alg.jianzhioffer.round2;

/**
 * 这个题绝对不应该是简单，起码中等
 * */
public class _29_clock_wise_print_matrix {
    /**
     * 我记着是搞四个变量
     * */
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return new int[0];
        int left = 0, right = matrix[0].length - 1;
        int top = 0, bottom = matrix.length - 1;
    
        int[] res = new int[matrix.length * matrix[0].length];
        int cur = 0;
        while (left <= right && top <= bottom) {
            for (int i = left; i <= right ; i++) {
                res[cur++] = matrix[top][i];
            }
            for (int i = top + 1; i <= bottom; i++) {
                res[cur++] = matrix[i][right];
            }
            if (top < bottom && left < right) {
                for (int i = right - 1; i >= left ; i--) {
                    res[cur++] = matrix[bottom][i];
                }
                for (int i = bottom - 1; i > top ; i--) {
                    res[cur++] = matrix[i][left];
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return res;
    }
    
    // 路飞比我背的短点
    /**
    * 改了无数次，委屈啊
    * */
    public int[] spiralOrder1(int[][] matrix) {
        if (matrix.length == 0) return new int[0];
        int left = 0, right = matrix[0].length - 1;
        int top = 0, bottom = matrix.length - 1;
    
        int[] res = new int[matrix.length * matrix[0].length];
        int cur = 0;
        while (true) {
            for (int i = left; i <= right ; i++) {
                res[cur++] = matrix[top][i];
            }
            if (++top > bottom)
                break;
            for (int i = top; i <= bottom; i++) {
                res[cur++] = matrix[i][right];
            }
            if (--right < left)
                break;
            for (int i = right; i >= left ; i--) {
                res[cur++] = matrix[bottom][i];
            }
            if (--bottom < top)
                break;
            for (int i = bottom; i >= top ; i--) {
                res[cur++] = matrix[i][left];
            }
            if (++left > right)
                break;
        }
        return res;
    }
}
